package com.android.log;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;

import com.android.file.FileHandler;
import com.android.file.RecordsPath;
import com.android.permission.rom.RomType;
import com.android.permission.rom.RomUtils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: CrashHandler
 * @Desciption: 异常抓取
 * @author: yichaohua
 * @date: 2018-04-11
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private static final String TAG = "CrashHandler";

    // CrashHandler实例
    private static CrashHandler instance;

    // 程序的Context对象
    private Context mContext;

    // 用来存储设备信息和异常信息
    private Map<String, String> infos = new HashMap<String, String>();

    // 用于格式化日期,作为日志文件名的一部分
    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    private final static String UNCAUGHT_RESTART_CLASS_NAME = "com.shushan.launcher.Launcher";


    private CrashHandler(){

    }


    public static CrashHandler getInstance(){

        if(instance == null){
            instance = new CrashHandler();
        }

        return instance;
    }

    /**
     * 初始化
     *
     * @param context
     */
    public void init(Context context) {

        mContext = context;

        // 设置该CrashHandler为程序的默认处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }


    @Override
    public void uncaughtException(Thread thread, Throwable ex) {

        handleException(ex);

    }


    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }

        // 收集设备参数信息
        collectDeviceInfo(mContext);

        // 保存日志文件
        return saveCrashInfoFile(ex);
    }


    public void collectDeviceInfo(Context ctx) {

        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null"
                        : pi.versionName;
                String versionCode = pi.versionCode + "";
                infos.put("versionName", versionName);
                infos.put("versionCode", versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                infos.put(field.getName(), field.get(null).toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private boolean saveCrashInfoFile(Throwable ex) {
        StringBuffer sb = new StringBuffer();
        sb.append("\n");
        sb.append("=============================================\n");
        SimpleDateFormat dtformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        sb.append(dtformat.format(Calendar.getInstance().getTime()));

        sb.append("\n");
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\n");
        }
        sb.append("\n*******************************************\n");
        sb.append("Exception:\n");

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        sb.append(result);

        String date = formatter.format(new Date());

        FileHandler fileHandler = FileHandler.getInstance();
        return fileHandler.write(RecordsPath.app_log + date + ".txt", sb.toString().getBytes(),true);
    }
}
